﻿if (typeof Axis.Admin == "undefined") Axis.Admin = {};
if (typeof Axis.Admin.QuestionPath == "undefined") Axis.Admin.QuestionPath = {};
Axis.Admin.QuestionPath.Entry = {
    CurrentPath: [],
    OldPath: [],
    /*CurrentPath: [{ ID: 1,Type:1, Res: [{ R: 1, C: 1 }, { R: 1, C: 1}]}]
    Ques: câu số mấy
    Res: mang cau tra lời ,mở rộng cho ma trận, nếu là ma trận có tham số trả lời C    
    */
    ListQuestion: [],
    CreateNextQuestion: function (themthamsonextquestion) {
        var thisObj = this;
        var objQues = $('#cboNextQuestion option:selected');
        var QuestionID = objQues.val();
        if (QuestionID == '-1' || QuestionID == '-100') return;
        var QuestionText = objQues.attr('QuestionText');
        var QuestionType = objQues.attr('QuestionType');
        var ScaleFromText = objQues.attr('ScaleFromText');
        var ScaleToText = objQues.attr('ScaleToText');
        var ScaleFrom = objQues.attr('ScaleFrom');
        var ScaleTo = objQues.attr('ScaleTo');
        var QuestionZOrder = objQues.text();
        thisObj.GetListOption({ ID: QuestionID, ZOrder: QuestionZOrder, Type: QuestionType, Text: QuestionText, ScaleFromText: ScaleFromText, ScaleToText: ScaleToText, ScaleFrom: ScaleFrom, ScaleTo: ScaleTo });

    },
    CreateListNextQuestion: function () {
        var thisObj = this;
        var list = [];
        var m = thisObj.CurrentPath.length;
        var n = thisObj.ListQuestion.length;
        for (var i = 0; i < n; i++) {
            var flag = 0;
            for (var j = 0; j < m; j++) {
                if (thisObj.ListQuestion[i].ID == thisObj.CurrentPath[j].ID)
                    flag = 1;
            }
            if (flag == 0)
                list.push(thisObj.ListQuestion[i]);
        }

        var htmlOption = "<option value='-1'>...</option>";
        $.each(list, function (index, item) {
            htmlOption += $.string.Format("<option value='{0}' QuestionType='{2}' QuestionText='{3}' ScaleFromText='{4}' ScaleToText='{5}' ScaleFrom='{6}'  ScaleTo='{7}' >{1}</option>", item.ID, item.ZOrder, item.Type, item.QuestionText, item.ScaleFromText, item.ScaleToText, item.ScaleFrom, item.ScaleTo);
        });
        htmlOption += "<option value='-100'>Kết thúc tại đây</option>";
        $("#cboNextQuestion").html(htmlOption);
    },
    GetListOption: function (objData) {
        var thisObj = this;
        var pData = '{' + $.string.Format('"QuestionID":{0}', objData.ID) + '}';
        $.ajax({
            url: 'Service/ResponseOptionService.asmx/GeResponseOptionByQuestionID',
            type: 'POST',
            data: pData,
            cache: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (pData, textStatus, jqXHR) {
                data = eval("(" + pData.d + ")");
                if (data) {
                    thisObj.ShowListOptionByQuestion(objData, data);
                }
                thisObj.CurrentPath.push({ ID: objData.ID, Type: objData.Type });
                thisObj.CreateListNextQuestion();
                var arrTemp = [];
                for (var i = 0; i < thisObj.OldPath.length; i++) {
                    if (thisObj.OldPath[i].ID != objData.ID)
                        arrTemp.push(thisObj.OldPath[i]);
                    else {
                        if (thisObj.OldPath[i].Res != undefined)
                            $.each(thisObj.OldPath[i].Res, function (index, item) {
                                $($.string.Format('input[question="{0}"][value="{1}"]', thisObj.OldPath[i].ID, item)).attr("checked", "checked");
                            });

                    }
                }
                thisObj.OldPath = arrTemp;
                console.log('thisObj.OldPath.length ', thisObj.OldPath.length);
                if (thisObj.OldPath.length > 1) {
                    $('#cboNextQuestion').val(thisObj.OldPath[0].ID);
                    thisObj.CreateNextQuestion();
                }
                if (thisObj.OldPath.length == 1) {
                    $('#cboNextQuestion').val(thisObj.OldPath[0].ID);
                    thisObj.CreateNextQuestion();
                    console.log('thisObj.OldPath.length == 1', thisObj.OldPath[0].NextQuestionnaireID);
                    $('#cboNextQuestion').val(thisObj.OldPath[0].NextQuestionnaireID);
                }
            },
            beforeSend: function (jqXHR, settings) {
            },
            error: function (jqXHR, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
            }
        });
    },
    ShowListOptionByQuestion: function (objData, data) {
        //    console.log(objData, data);
        var objThis = this;
        var type = parseInt(objData.Type + '');
        var divQuestionText = document.createElement('div'); //document.createElement("BUTTON");
        $(divQuestionText).addClass('DivQuestion');
        $(divQuestionText).addClass('new-row');
        $(divQuestionText).html($.string.Format("Câu số {0}:<div class='Question'>{1}</div>", objData.ZOrder, objData.Text));
        $("#divNextQuestion").before($(divQuestionText));
        var divAnswer = document.createElement('div');
        $(divAnswer).addClass('new-row');
        $(divAnswer).addClass('divAnswer');
        $(divAnswer).attr("Question", objData.ID);
        $(divAnswer).attr("Type", objData.Type);
        $(divAnswer).insertAfter($(divQuestionText));
        $(divQuestionText).append($.string.Format('<div title="Xóa câu" class="sprited ss-formwidget-delete-icon" Question="{0}" onclick="DeleteQuestion(this)">&nbsp;</div>', objData.ID));
        switch (type) {
            case 0:
                //SA
            case 2:
                //True/Flase
                $.each(data, function (index, item) {
                    var note = document.createElement('div');
                    var radioNote = document.createElement('input');
                    $(radioNote).attr('type', 'radio');
                    $(radioNote).attr('name', 'Question' + objData.ID);
                    $(radioNote).attr('Question', objData.ID);
                    $(radioNote).attr('value', item.Value);
                    $(note).append(radioNote);
                    $(note).append(item.Caption);
                    $(divAnswer).append($(note));
                });
                break;
            case 1:
                //MA
                $.each(data, function (index, item) {
                    var note = document.createElement('div');
                    var radioNote = document.createElement('input');
                    $(radioNote).attr('type', 'checkbox');
                    //
                    $(radioNote).attr('Question', objData.ID);
                    $(radioNote).attr('value', item.Value);
                    $(note).append(radioNote);
                    $(note).append(item.Caption);
                    $(divAnswer).append($(note));
                });
                break;
            case 3:
                var note = document.createElement('div');
                var radioNote = document.createElement('input');
                $(radioNote).attr('type', 'text');
                $(note).append(radioNote);
                $(divAnswer).append($(note));
                break;
            case 4:
                var scaleHeader = $.string.Format('<div class="scale-header"> <ul><li><label>&nbsp;<label></li>', objData.ScaleFromText);
                var ScaleFrom = parseInt(objData.ScaleFrom + '');
                var ScaleTo = parseInt(objData.ScaleTo + '');
                for (var i = ScaleFrom; i <= ScaleTo; i++)
                    scaleHeader += $.string.Format('<li><label>{0}</label></li>', i);
                scaleHeader += $.string.Format('<li><label>&nbsp;</label></li></ul></div>', objData.ScaleToText);
                $(divAnswer).append(scaleHeader);
                var scaleBody = document.createElement('div');
                $(scaleBody).addClass('scale-body');
                var ulNode = document.createElement('ul');
                $(scaleBody).append($(ulNode));
                $(ulNode).append($.string.Format('<li><label>{0}<label></li>', objData.ScaleFromText));
                for (var i = ScaleFrom; i <= ScaleTo; i++) {
                    var liNode = document.createElement('li');
                    var radioNote = document.createElement('input');
                    $(radioNote).attr('type', 'radio');
                    //   $(radioNote).attr('name', 'Question' + objData.ID);
                    $(radioNote).attr('Question', objData.ID);
                    $(radioNote).attr('value', i);
                    $(liNode).append(radioNote);
                    $(ulNode).append($(liNode));
                }
                $(ulNode).append($.string.Format('<li><label>{0}<label></li>', objData.ScaleToText));
                $(divAnswer).append($(scaleBody));
                break;
            case 5:
                //Matrix
                var projectID = $("#ctl00_AdministratorBody_ddlProjectList").val();
                var thisObj = this;
                var pData = '{' + $.string.Format('"QuestionID":{0},"ProjectID":{1}', objData.ID, projectID) + '}';
                $.ajax({
                    url: 'Service/ResponseOptionService.asmx/GetQuestionListID',
                    type: 'POST',
                    data: pData,
                    cache: false,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (pData, textStatus, jqXHR) {
                        QuesCol = eval("(" + pData.d + ")");
                        var RowHeader = '<div class="scale-header"> <ul><li><label>&nbsp;<label></li>';

                        $.each(data, function (i, item) {
                            RowHeader += $.string.Format('<li><label>{0}</label></li>', item.Caption);
                        });
                        RowHeader += '<li><label>&nbsp;</label></li></ul></div>';
                        $(divAnswer).append(RowHeader);
                        $.each(QuesCol, function (i, item) {
                            if (i > 0) {
                                var scaleBody = document.createElement('div');
                                $(scaleBody).addClass('scale-body');
                                var ulNode = document.createElement('ul');
                                $(scaleBody).append($(ulNode));
                                $(ulNode).append($.string.Format('<li><label>{0}<label></li>', item.QuestionText));
                                $.each(data, function (j, item2) {
                                    var liNode = document.createElement('li');
                                    var radioNote = document.createElement('input');
                                    $(radioNote).attr('type', 'radio');
                                    $(radioNote).attr('name', 'QuestionMatrix' + item.ID);
                                    $(radioNote).attr('value', +i + "_" + j);
                                    $(liNode).append(radioNote);
                                    $(ulNode).append($(liNode));
                                });
                                $(divAnswer).append($(scaleBody));
                            }
                        });


                    },
                    beforeSend: function (jqXHR, settings) {
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                    },
                    complete: function (XMLHttpRequest, textStatus) {
                    }
                });
                break;
        }
    },
    LoadPathDetail: function (opt) {
        var thisObj = this;
        var projectID = $("#ctl00_AdministratorBody_ddlProjectList").val();
        var pData = '{' + $.string.Format('"ProjectID":{0},"PathID":{1}', projectID, opt.ID) + '}';
        $.ajax({
            url: 'Service/ManagerQuestionService.asmx/GetPathDetailList',
            type: 'POST',
            data: pData,
            cache: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function (jqXHR, settings) {
                thisObj.OldPath = [];
                $(".DivQuestion").remove();
                $(".divAnswer").remove();
            },
            success: function (pData, textStatus, jqXHR) {
                var objData = eval("(" + pData.d + ")");
                $.each(objData, function (index, item) {
                    var flag = 0;
                    $.each(thisObj.OldPath, function (i, node) {
                        if (node.ID == item.QuestionnaireID)
                            flag++;
                    });
                    if (flag == 0)
                        thisObj.OldPath.push({ 'ID': item.QuestionnaireID, NextQuestionnaireID: item.NextQuestionnaireID });
                });

                $.each(thisObj.OldPath, function (i, node) {
                    var ArrAswser = [];
                    $.each(objData, function (index, item) {
                        if (node.ID == item.QuestionnaireID)
                            ArrAswser.push(item.ResponseValue);
                    });
                    node.Res = ArrAswser;
                });

                if (thisObj.OldPath.length > 1) {
                    $('#cboNextQuestion').val(thisObj.OldPath[0].ID);
                    thisObj.CreateNextQuestion();
                }
                console.log('thisObj.OldPath.length == 1', thisObj.OldPath[0].NextQuestionnaireID);
                if (thisObj.OldPath.length == 1) {
                    $('#cboNextQuestion').val(thisObj.OldPath[0].ID);
                    thisObj.CreateNextQuestion();
                  
                    $('#cboNextQuestion').val(thisObj.OldPath[0].NextQuestionnaireID);
                }

            },
            error: function (jqXHR, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
            }
        });
    },
    Reset: function () {
        thisObj = Axis.Admin.QuestionPath.Entry
        $(".divAnswer, .DivQuestion").remove();
        thisObj.LoadListQuestion();
        thisObj.CurrentPath = [];
        thisObj.ListQuestion = [];
        $("#cboStatus").val(0);
        $("#txtContent").val('');
        $("#txtName").val('');
        $("#txtID").val('');
    },
    Update: function (type, opts) {
        var thisObj = this;
        var data = { ID: $("#txtID").val(), Description: $("#txtContent").val(), ProjectID: $("#ctl00_AdministratorBody_ddlProjectList").val(), Status: $("#cboStatus").val(), Name: $("#txtName").val(), Stop: $("#cboNextQuestion").val(), ZOrder: $("#cboZOrder").val() };
        data.Action = type;

        var ResponseOption = "";
        var ret = "{ResponseOption:[";
        $.each($(".divAnswer"), function (index, item) {
            var question = $(item).attr('question');
            var questionType = parseInt($(item).attr('type'));
            ret += "{";
            ret += $.string.Format("QuestionID:'{0}',", question);
            ret += $.string.Format("QuestionType:'{0}'", questionType);
            var ResponseValue = "";
            switch (questionType) {
                case 0: //SA
                case 2: //True/False
                case 4: //Scale
                    $.each($($.string.Format('input:radio[question="{0}"]:checked', question)), function (index, item) {
                        ResponseValue += $(this).val() + ',';
                    });
                    if (ResponseValue.length > 0)
                        ResponseValue = ResponseValue.substr(0, ResponseValue.length - 1);
                    ret += $.string.Format(",ResponseValue:'{0}'", ResponseValue);
                    break;
                case 1: //Checkbox        
                    $.each($($.string.Format('input:checkbox[question="{0}"]:checked', question)), function (index, item) {
                        ResponseValue += $(this).val() + ',';
                    });
                    if (ResponseValue.length > 0)
                        ResponseValue = ResponseValue.substr(0, ResponseValue.length - 1);
                    ret += $.string.Format(",ResponseValue:'{0}'", ResponseValue);
                    break;
            }
            ret += "},";
        });
        if (ret != "{ResponseOption:[")
            ret = ret.substr(0, ret.length - 1);
        ret += "]}";

        data.Action = type;
        data.ResponseOption = ret;
        if (type == 'INSERT')
            data.ID = "0";
        if (type == 'DELETE')
            data.ID = opts.ID;
        $.Ajax({
            url: 'Service/QuestionPathService.ashx',
            type: 'POST',
            data: data,
            success: function (data, textStatus, jqXHR) {
                if (data) {
                    data = eval("(" + data + ")");
                    if (data.IsSuccessfull) {
                        Axis.Admin.QuestionPath.List.Grid.Reload();
                    }
                }
            },
            beforeSend: function (jqXHR, settings) {
            },
            error: function (jqXHR, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
            }
        });
    },
    DeleteQuestion: function (obj) {
        var thisObj = this;
        var Ques = $(obj).attr('question');
        var Question = $(obj).parent();
        var Answer = $(Question).next();
        $(Question).remove();
        $(Answer).remove();
        var pos = -1;
        $.each(thisObj.CurrentPath, function (index, item) {
            if (item.ID == Ques)
                pos = index;
        });
        if (pos > -1)
            thisObj.CurrentPath.splice(pos, 1);
        thisObj.CreateListNextQuestion();
    },
    LoadListQuestion: function () {
        var projectID = $("#ctl00_AdministratorBody_ddlProjectList").val();
        var thisObj = this;
        var pData = '{' + $.string.Format('"ProjectID":{0}', projectID) + '}';
        $.ajax({
            url: 'Service/ManagerQuestionService.asmx/GetQuestionList',
            type: 'POST',
            data: pData,
            cache: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function (jqXHR, settings) {
                thisObj.ListQuestion = [];
            },
            success: function (pData, textStatus, jqXHR) {
                thisObj.ListQuestion = eval("(" + pData.d + ")");
                thisObj.CreateListNextQuestion();
                //  thisObj.CreateNextQuestion();
            },


            error: function (jqXHR, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
            }
        });
    }
};
function CreateQuestion() {
    Axis.Admin.QuestionPath.Entry.CreateNextQuestion();
}
function DeleteQuestion(obj) {
    Axis.Admin.QuestionPath.Entry.DeleteQuestion(obj);
}